package com.sam.java;


/**
 * Created by samwang on 2018/4/7.
 */
public class NotifyNotifyall {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        for (int i = 0; i < 3; i++) {
            new Thread(runnable, "T" + i).start();
        }
    }

    static class MyRunnable implements Runnable {
        boolean isFirst = true;
        int count = 0;
        @Override
        public void run() {
            while (true) {

                    try {
                        synchronized (this) {
                            if (isFirst && "T0".equals(Thread.currentThread().getName())) {
                                isFirst = false;
                            } else {
                                System.out.println(Thread.currentThread().getName()+"进入等待"+count);
                                this.wait();
                            }
                        }

                        System.out.println(Thread.currentThread().getName()+"运行"+count);
                        Thread.sleep(200);
                        synchronized (this) {
//                            if (isFirst && "T0".equals(Thread.currentThread().getName())) {
//                                isFirst = false;
//                                System.out.println(Thread.currentThread().getName() + "运行完成释放全部" + count);
//                                this.notifyAll();
//                            } else {
                                System.out.println(Thread.currentThread().getName() + "运行完成唤醒一个" + count);
                                this.notify();
//                            }
                        }
                        count++;
                        if (count >= 20) {
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

            }
        }
    }



}
